# -*- coding: UTF-8 -*-
# ! /usr/bin/env python

import rsa
from Crypto.Cipher import PKCS1_v1_5
import base64
from Crypto.PublicKey import RSA
import OpenSSL.crypto


import backend.encryption.myrsa
# 使用 rsa库进行RSA签名和加解密
from OpenSSL import crypto
from ssl import PEM_cert_to_DER_cert, DER_cert_to_PEM_cert  # standard library

from backend.encryption import myrsa

PRIVATE_KEY_PATH = r'./channPri.p12'
PUBLIC_KEY_PATH = r'./channPub.der'


def get_public_key(PUBLIC_KEY_PATH):
    """
    从cer证书中提取公钥方法
    :param cer_file: cer证书存放的路径
    :return: 公钥

    with open("./mypath/data") as f:
    print(f.read())
    """

    with open(PUBLIC_KEY_PATH, "rb") as f:
        der = f.read()

    x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, der)
    pkey = x509.get_pubkey()

    pkey.bits()

    pkey.type() == OpenSSL.crypto.TYPE_RSA
    # # cert = crypto.load_certificate(crypto.FILETYPE_ASN1, open(PUBLIC_KEY_PATH, "rb").read())    # 原版
    # cert = crypto.load_certificate(crypto.FILETYPE_PEM, open(PUBLIC_KEY_PATH).read())    # 修改版
    # res = crypto.dump_publickey(crypto.FILETYPE_PEM, cert.get_pubkey()).decode("utf-8")

    PEMCERT = DER_cert_to_PEM_cert(der)
    print("der2pem")
    print(PEMCERT)

    print(pkey)
    print(1)
    res = crypto.dump_publickey(crypto.FILETYPE_PEM, pkey).decode("utf-8")
    print(res.strip())
    print(44444)
    return res.strip()


# data2 = '''
# {
# "accountName":"高靖宇",
#
# }
# '''

def get_private_key(PRIVATE_KEY_PATH, password="123456"):
    """
    从pfx证书中提取私钥方法,如果证书已加密，需要输入密码
    :param pfx_file_path:pfx证书存放的路径
    :param password:证书密码
    :return:私钥pkey = Crypto.load_pkcs12(key, password).get_privatekey()
    """
    pfx = crypto.load_pkcs12(open(PRIVATE_KEY_PATH, 'rb').read(), bytes(password, encoding="utf8"))
    res = crypto.dump_privatekey(crypto.FILETYPE_PEM, pfx.get_privatekey()).decode("utf-8")
    print("a1")
    print(pfx)
    print(res)
    print("aaaaa")
    print(res.strip())

    # res = crypto.dump_privatekey(crypto.FILETYPE_PEM, pfx.get_privatekey())
    return res.strip()


def cipher(msg):
    """
    公钥加密
    :param msg: 要加密内容
    :return:  加密之后的密文
    """
    # 获取钥匙加密
    # key = get_public_key(PUBLIC_KEY_PATH)
    # key = get_private_key(pfx_file_path)
    # publickey = res.strip()
    # 获取钥匙加密
    key = get_public_key(PUBLIC_KEY_PATH)

    key2 = get_private_key(PRIVATE_KEY_PATH)
    publickey = RSA.importKey(key)
    # 分段加密
    pk = PKCS1_v1_5.new(publickey)
    encrypt_text = []

    for i in range(0, len(msg), 100):
        cont = msg[i:i + 100]
        print(cont.encode())
        encrypt_text.append(pk.encrypt(cont.encode()))
    # 加密完进行拼接
    cipher_text = b''.join(encrypt_text)
    # base64进行编码
    result = base64.b64encode(cipher_text)
    return result.decode()


# miwen = cipher(data2)
# # 输出密文
# print('生成的密文：\n', miwen)
def long_decrypt(msg):
    """
    私钥解密
    """

    msg = base64.b64decode(msg)
    # print(msg)
    length = len(msg)

    default_length = 128
    # 私钥解密
    priobj = PKCS1_v1_5.new(RSA.importKey(get_private_key(PRIVATE_KEY_PATH)))

    # 长度不用分段
    if length < default_length:
        return b''.join(priobj.decrypt(msg, b'Decryption failure'))
    # 需要分段
    offset = 0
    res = []
    while length - offset > 0:
        if length - offset > default_length:  # 512-0>256
            res.append(priobj.decrypt(msg[offset:offset + default_length], b'Decryption failure'))
        else:
            res.append(priobj.decrypt(msg[offset:], b'Decryption failure'))
        offset += default_length
    return b''.join(res).decode('utf8')


"""
测试代码
"""
# if __name__ == '__main__':
#     # a="gaojingyu"

#     jiamia =cipher(data5)
#     aaaa = 'PhErBJY0lbGjRGX0za5WJQt7B5P1QsY9rCnZsQZIKoYNYA7ziuXAYUQKzV2FsQ/QAvIdxDddIA8xLNvzbpjxVBdMvS/5Gz5n+rPGYl6x6sV5wi3o7KWzCPiNDD/6ImdtAm+xjG+625dtagIb/cxgvWC2TfVrNldMxr85u0GeSSo='
#     print("加密结果"+jiamia)
#     print("123abc"
#           "")
#     #
#     # BBB='0nK0tEe+1g0VECXFmqut517RZSRmdZfSKCHz52rASNFoalQp2VjNjbaqeGEu1Hct/XGuyl4MuKDEbnVF2Yc1KDh5RgP69kOUZO0Q7UST+Brk6txH8I+9X9sPQlZQobcu2Sxnh7qyyI5eegBu/phlICl+HRaf3rXR+i55X0PpywY='
#     #
#     JM = long_decrypt(jiamia)
#     print("解密结果")
#     print(JM)




class Encrypt(object):
    def __init__(self, e, m):
        self.e = e
        self.m = m

    def encrypt(self, message):
        mm = int(self.m, 16)
        ee = int(self.e, 16)
        with open(PUBLIC_KEY_PATH, "rb") as f:
            der = f.read()
        x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, der)
        pkey = x509.get_pubkey()
        print(pkey)
        rsa_pubkey =pkey(mm, ee)
        crypto = self._encrypt(message.encode(), rsa_pubkey)
        return crypto.hex()

    def _pad_for_encryption(self, message, target_length):
        message = message[::-1]
        max_msglength = target_length - 11
        msglength = len(message)
        padding = b''
        padding_length = target_length - msglength - 3
        for i in range(padding_length):
            padding += b'\x00'
        return b''.join([b'\x00\x00', padding, b'\x00', message])

    def _encrypt(self, message, pub_key):
        keylength = rsa.common.byte_size(pub_key.n)
        padded = self._pad_for_encryption(message, keylength)
        payload = rsa.transform.bytes2int(padded)
        encrypted = rsa.core.encrypt_int(payload, pub_key.e, pub_key.n)
        block = rsa.transform.int2bytes(encrypted, keylength)
        return block

    def encrypt(e, m, message):
        en = Encrypt(e, m)
        return en.encrypt(message)




if __name__ == '__main__':
    data5 = '''
      "orderStatusList": [
           {

               "bankInCode": "234",
               "sourceCode": "20200927520",
               "orderStatus": "20201229",
               "mark1": "demoData",
               "mark2": "demoData",
               "mark3": "demoData",
               "mark4": "demoData",
               "mark5": "demoData"
           }
       ]
       '''






